package com.iamteer.day18.batch;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class AdminDao {
	//全局参数
	private Connection con;
	private PreparedStatement pstmt;
	private ResultSet rs;
	
	private String url = "jdbc:mysql:///day18";
	private String user = "root";
	private String password = "123456";
	public void save(List<Admin> list) {
		//SQL
		String sql = "INSERT INTO admin(username,password) VALUES(?,?)";
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(url, user, password);
			
			pstmt = con.prepareStatement(sql);
			
			//预编译 SQL 语句
			for (int i = 0; i < list.size(); i++) {
				Admin admin = list.get(i);
				pstmt.setString(1, admin.getUsername());
				pstmt.setString(2, admin.getPassword());
				
				//添加批处理
				pstmt.addBatch();
				
				//不需要传入 sql
				//每 5 条执行一次
				if (i % 5 == 0) {
					pstmt.executeBatch();
					pstmt.clearBatch();
				}
				
				pstmt.executeBatch();
				pstmt.clearBatch();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(rs != null){
					rs.close();
				}
				if(pstmt != null){
					pstmt.close();
				}
				if(con != null){
					con.close();
				}
			} catch (SQLException e) {
				throw new RuntimeException(e);
			}
		}
	}
}
